import { mapGetters } from 'vuex'
import { getdeptlist, getAlluser, filestemplate, getGangweiList, findTypeByProcessType, getrenyuanList, getappToken } from '@/api/myapi/common'
import { remove, getguifanList } from '@/api/myapi/tixiwenjian'
const pageData = require('./pageDefaultData.js')
const moment = require('moment')
const bassUrl = 'http://47.94.218.36:9000/jingkang'
// const bassUrl="http://118.195.193.214:9000/jingkang";
const mixin = {
  data() {
    return {
      serviceUrl: 'http://47.94.218.36',
      expandRowkeys: [],
      privateKeyHolder: '', //  申请解密的文件私钥持有人
      processType: '', //   申请解密的过程状态
      rowFileList: [], //  申请解密的文件
      processId: '', //  申请解密的流程
      gongzuoFilesId: '', // 文件解密  id
      unitList: ['g', 'mg', 'Kg', 'l', 'ml', '只', '台'],
      checkItem: {}, //  未通过原因
      deptOption: [], //   部门列表
      Alluser: [], //   所有人员
      userList: [], //   不带部门人员
      filestemplateList: [], //  文件模板
      gangweiList: [], //   岗位列表
      bdheight: window.innerHeight,
      bdwidth: window.innerWidth,
      invalidStatusList: pageData.invalidStatusList,
      fileTypeList: pageData.fileTypeList,
      progressTypes: pageData.progressTypes,
      progressNameTypes: pageData.progressNameTypes,
      fileprogressNameTypes: pageData.fileprogressNameTypes,
      progressLists: pageData.progressLists,
      processStatusList: pageData.processStatusList,
      controlStatusList: pageData.controlStatusList,
      shebeiclassList: pageData.shebeiclassList,
      shebeiShowList: pageData.shebeiShowList,
      calibrationStatusList: pageData.calibrationStatusList,
      purchaseList: pageData.purchaseList,
      environmentList: pageData.environmentList,
      sampleList: pageData.sampleList,
      dealTypeList: pageData.dealTypeList,
      aql: pageData.aql,
      numLists: pageData.numLists,
      liushuihao: '', //  编号流水值
    }
  },
  computed: mapGetters(['userInfo', 'permission', 'materialNumberType', 'batchNumberType', 'versionNumberType', 'serialNumberType', 'sterilizeNumberType', 'numberType', 'tenantId', 'screenWidth']),
  filters: {
    // 手机号脱敏
    hidetel(val) {
      if (val) {
        let str1 = val.substr(0, 3)
        let str2 = val.substr(7, 4)
        return str1 + '****' + str2
      }
    },
    // 手机号脱敏
    hideName(val) {
      if (val) {
        let str1 = val.substr(0, 1)
        let str2 = val.substr(-1, 1)
        return str1 + '****' + str2
      }
    },
    // 代码格式化
    getHtml(val) {
      let a = '' + val
      let str = a
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/&quot;/g, '"')
        .replace(/&apos;/g, "'")
      console.log(str)
      return str
    },
    //  字符串切割
    overWord(val, len) {
      if (val) {
        if (val.length > len) {
          return val.substr(0, len) + '...'
        }
      }
      return val
    },
  },
  methods: {
    birthdayChange(val, form) {
      console.log(val)
      if (val) {
      } else {
      }
    },
    closeShow(type) {
      this[type] = false
      this.$nextTick(() => {
        let $table = this.$refs.table
        if ($table) {
          for (let $i = 0; $i < this.tableData.length; $i++) {
            let $td = this.tableData[$i]
            if (this.expandRowkeys.includes($td.id)) {
              $table.toggleRowExpansion($td, true)
              $td.expansion = true
            }
          }
        }
      })
    },
    //  列表 行折叠  (可展开多个)
    toogleExpand(row) {
      if(row.expansion){
        row.expansion=false;
        if(this.expandRowkeys.includes(row.id)) {
          this.expandRowkeys.splice(this.expandRowkeys.indexOf(row.id))  
        }
      }else{
        row.expansion = true
        this.expandRowkeys.push(row.id)
      }
      let $table = this.$refs.table
      $table.toggleRowExpansion(row)
    },
    // table自适应列宽
    getAdaptionWidth(prop, tableData,min=100) {
      // 判断传递的数据是否可用
      // console.log("getAdaptionWidth",prop, tableData, min)
      if (!Array.isArray(tableData) || tableData.length === 0) {
        return
      }
      if (!prop || !prop.length || prop.length === 0) {
        return
      }
      // 接收两个参数 prop为列的属性值  tableData为表格数据源
      prop = prop + ''
      let columnContent = ''
      // 获取该列中最长的数据(内容)
      let index = 0
      for (let i = 0; i < tableData.length; i++) {
        if (!tableData[i][prop]) {
          return min + 'px'
        }
        const now_text = tableData[i][prop] + ''
        const max_text = tableData[index][prop] + ''

        if (now_text.length > max_text.length) {
          index = i
        }
      }
      // 获取到的最长的列的内容
      columnContent = tableData[index][prop]
      // // 以下分配的单位长度可根据实际需求进行调整
      let columnWidth = 0
      for (const char of columnContent) {
        if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
          // 如果是英文字符，为字符分配10个单位宽度
          columnWidth += 10
        } else if (char >= '\u4e00' && char <= '\u9fa5') {
          // 如果是中文字符，为字符分配20个单位宽度
          columnWidth += 16
        } else {
          // 其他种类字符，为字符分配10个单位宽度
          columnWidth += 10
        }
      }
      if (columnWidth < min) {
        // 设置最小宽度
        columnWidth = min
      }
      if (columnWidth > 260) {
        // 设置最大宽度
        columnWidth = 260
      }
      return columnWidth + 'px'
    },
    //查看
    handleShow(row) {
      this.detailId = row.id
      this.show = true
    },
    toDel(row) {
      sessionStorage.setItem('delItem', JSON.stringify(row))
      this.pushTo('/wenjianzuofei/list')
    },
    //  文件 解密申请
    applyShow(row, type) {
      if (type == 'file') {
        this.rowFileList = [row]
        this.processType = ''
        this.gongzuoFilesId = row.gongzuoFilesId
      } else {
        this.rowFileList = row.jiluFileList
        this.processType = row.processType
        this.gongzuoFilesId = ''
      }
      this.privateKeyHolder = row.privateKeyHolder
      this.processId = row.id
      this.openDialg('encryption')
    },
    //   wps 对接 1 文件上传 2流程选择 3 审核 4  文件流 5 升版
    preContent(item, type) {
      console.log(item)
      console.log(type)
      sessionStorage.setItem('fileName', item.name)
      let fileId = '',
        filePath = ''
      if (type == 1 || type == 5) {
        fileId = item.templateFile.replace(bassUrl, '').split('/')[3].split('.')[0]
        filePath = item.templateFile.replace(bassUrl, '')
      }
      if (type == 2) {
        fileId = item.templateFilex.replace(bassUrl, '').split('/')[3].split('.')[0]
        filePath = item.templateFilex.replace(bassUrl, '')
      }
      if (type == 3) {
        fileId = item.pdfTemplateFileBeifen.replace(bassUrl, '').split('/')[3].split('.')[0]
        filePath = item.pdfTemplateFileBeifen.replace(bassUrl, '')
      }
      if (type == 4) {
        fileId = item.pdfTemplateFile.replace(bassUrl, '').split('/')[3].split('.')[0]
        filePath = item.pdfTemplateFile.replace(bassUrl, '')
      }
      if (type == 6) {
        //  文件模板
        console.log(item.url.indexOf('http'))
        if (item.url.indexOf('http') != -1) {
          fileId = item.url.replace(bassUrl, '').split('/')[3].split('.')[0]
          filePath = item.url.replace(bassUrl, '')
        } else {
          fileId = item.url.split('/')[2].split('.')[0]
          filePath = item.url
        }
      }
      if (fileId) {
        let parmas = {
          _w_fileid: fileId,
          _w_fname: filePath,
        }
        console.log(parmas)
        getappToken(parmas).then(({ data }) => {
          sessionStorage.wpsUrl = data.wpsUrl
          sessionStorage.token = data.token
          const jump = this.$router.resolve({
            name: 'viewFile',
          })
          window.open(jump.href, '_blank')
        })
      } else {
        this.$message.error('当前文件缺少必要参数')
      }
    },
    //  删除
    confirmDel(row) {
      console.log(row)
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        remove(
          {
            ids: row.id,
          },
          this.system
        ).then(({ data }) => {
          if (data && data.success) {
            this.refreshList(this.pageNo)
            this.$message.success('删除成功')
          }
        })
      })
    },
    //  生产批号
    getBatchNumber(form, date) {
      form.batchNumber = 'S' + moment(date).format('YYYYMMDD') + this.liushuihao
    },
    //  原材料 批号
    getMaterialNumber(form, date) {
      form.materialNumber = 'Y' + moment(date).format('YYYYMMDD') + this.liushuihao
    },
    //  生成灭菌批号
    getSterilizeNumber(form, date) {
      form.sterilizeNumber = 'M' + moment(date).format('YYYYMMDD') + this.liushuihao
    },
    //   系统设置编号类型
    findTypeByProcessType(liushuihao, type) {
      let processType = Number(Object.values(this.progressLists).findIndex((item) => item == this.$route.name)) + 1
      if (liushuihao) {
        if (processType > 5) {
          if (type == 'materialNumber') {
            return 'Y' + moment(new Date()).format('YYYYMMDD') + this.liushuihao
          } else if (type == 'batchNumber') {
            return 'S' + moment(new Date()).format('YYYYMMDD') + this.liushuihao
          } else if (type == 'sterilizeNumber') {
            return 'M' + moment(new Date()).format('YYYYMMDD') + this.liushuihao
          } else {
            this.liushuihao = Number(liushuihao) + 1
            let pinNumber = this.liushuihao < 9 ? '0' + this.liushuihao : this.liushuihao + ''
            return this.numLists[processType] + moment(new Date()).format('YYYYMMDD') + pinNumber
          }
        } else {
          if (type == 'versionNumber') {
            return `A0`
          } else {
            this.liushuihao = Number(liushuihao) + 1
            let pinNumber = this.liushuihao < 9 ? '0' + this.liushuihao : this.liushuihao + ''
            return `${this.numLists[processType]}-${this.userInfo.deptCode}-${pinNumber}`
          }
        }
      }
      findTypeByProcessType({
        processType: processType,
      }).then(({ data }) => {
        if (data && data.success) {
          this.$store.commit('SET_MATERIALNUMBERTYPE', data.data.materialNumberType) //  原材料编号
          this.$store.commit('SET_VERSIONNUMBERTYPE', data.data.versionNumberType) // 文件版本号
          this.$store.commit('SET_BATCHNUMBERTYPE', data.data.batchNumberType) //  生产批号
          this.$store.commit('SET_SERIALNUMBERTYPE', data.data.serialNumberType) // 流水编号
          this.$store.commit('SET_STERILIZENUMBERTYPE', data.data.sterilizeNumberType) // 灭菌编号
          this.$store.commit('SET_NUMBERTYPE', data.data.fileNumberType)
          this.liushuihao = data.data.liushuihao
          if (processType <= 5) {
            this.formList[0].fileNumberType = data.data.fileNumberType
            this.formList[0].versionNumberType = data.data.versionNumberType
            if (data.data.fileNumberType == 0) this.formList[0].fileNumber = `${this.numLists[processType]}-${this.userInfo.deptCode}-${this.liushuihao}`
            if (data.data.versionNumberType == 0) this.formList[0].versionNumber = 'A0'
          } else {
            this.formList[0].numberType = data.data.fileNumberType
            this.formList[0].batchNumberType = data.data.batchNumberType
            this.formList[0].sterilizeNumberType = data.data.sterilizeNumberType
            this.formList[0].materialNumberType = data.data.materialNumberType
            if (data.data.fileNumberType == 0) this.formList[0].number = this.numLists[processType] + moment(new Date()).format('YYYYMMDD') + this.liushuihao
          }
          this.$forceUpdate()
        }
      })
    },
    // 所有人员
    getAlluser(type) {
      getAlluser({
        current: 1,
        size: 100000,
      }).then(({ data }) => {
        if (data && data.success) {
          this.userList = data.data.records
          data.data.records.forEach((item) => {
            this.Alluser.push({
              label: type ? `${item.deptName}/${item.name}` : `${item.deptName}/${item.postName}/${item.name}`,
              value: item.id,
              deptId: item.deptId,
            })
          })
        }
      })
    },
    // 部门列表
    getdeptlist() {
      getdeptlist({
        current: 1,
        size: 100000,
      }).then(({ data }) => {
        if (data && data.success) {
          this.deptOption = data.data
        }
      })
    },
    //   通过部门查用户
    getuserByDept(val, form, type) {
      // console.log(val)
      getrenyuanList({
        deptId: val,
      }).then(({ data }) => {
        if (data && data.success) {
          if (type) {
            this.memberOption = data.data.records
          } else {
            this.$set(form, 'memberOption', data.data.records)
          }
        }
      })
    },
    //  负责人
    selectChange(val, form) {
      let item = form.memberOption.find((item) => item.id == val)
      if (form.applyUserName) {
        form.applyUserName = item.name
      } else {
        form.manageUserName = item.name
      }
      this.$forceUpdate()
    },
    //  文件模板
    getFilestemplate() {
      filestemplate({}).then(({ data }) => {
        if (data && data.success) {
          this.filestemplateList = data.data.records
        }
      })
    },
    //   岗位
    getGangweiList() {
      getGangweiList({
        current: 1,
        size: 100000,
      }).then(({ data }) => {
        if (data && data.success) {
          this.gangweiList = data.data.records
        }
      })
    },
    //  设备信息
    getDevice() {
      const parmas = {
        current: 1,
        size: 10000,
        descs: 'create_time',
        isTongguo: 1,
      }
      getguifanList(parmas, 'deviceprocessdevice').then(({ data }) => {
        console.log('生产管理-设备')
        console.log(data)
        if (data && data.success) {
          this.deviceList = data.data.records
        }
      })
    },
    //    是否使用设备 添加
    addDeviceList(index) {
      this.formList[index].deviceList.push({
        deviceModel: '', //	设备型号		false
        deviceName: '', //	设备名称		false
        deviceNumber: '', //	设备编号
      })
    },
    // 是否使用设备 添加  删除
    deldevice(index, i) {
      this.formList[index].deviceList.splice(i, 1)
      if (this.formList[index].deviceList.length == 0) this.formList[index].isUser = 0
    },
    //   产品信息
    getproduct() {
      const parmas = {
        current: 1,
        size: 10000,
        descs: 'create_time',
        isTongguo: 1,
      }
      getguifanList(parmas, 'productprocessproduct').then(({ data }) => {
        console.log('产品管理-产品信息')
        console.log(data)
        if (data && data.success) {
          this.productList = data.data.records
        }
      })
    },
    // 文件转base64
    imageToBase64(file) {
      var reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        console.log('file 转 base64结果：' + reader.result)
        return reader.result
      }
      reader.onerror = function (error) {
        console.log('Error: ', error)
      }
    },
    // 上传图片
    upFile(file) {
      let data = new FormData()
      data.append('file', file.file)
    },
    // 代码格式化
    getHtml(val) {
      let a = '' + val
      let str = a
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/&quot;/g, '"')
        .replace(/&apos;/g, "'")
      console.log(str)
      return str
    },
    getString(val) {
      let otherImage = []
      if (val) {
        for (let i = 0; i < val.length; i++) {
          otherImage.push(val[i].path)
        }
        return JSON.stringify(otherImage)
        // return otherImage.join('|')
      }
    },
    // 改变父页面的值
    changeItem(obj, k, val) {
      this.$set(obj, k, val)
    },
    // 打开父页面聊天框
    dochat(item) {
      this.$parent.openChat(item)
    },
    pushTo(url) {
      // this.$store.commit('saveRoutetitle', 'home.giftshop')
      // location.href = url
      this.$router.push(url)
    },
    openDialg(ref) {
      this.$refs[ref].init()
    },
    back() {
      history.go(-1)
    },
    // 字符串转数字
    toNum(val) {
      if (parseFloat(val)) {
        return parseFloat(val)
      } else {
        return 0
      }
    },
    toDetail(url, id) {
      this.$router.push({
        path: url,
        query: {
          id: id,
        },
      })
    },
    openNew(path) {
      let routeUrl = this.$router.resolve(path)
      window.open(routeUrl.href, '_blank')
    },
    jump(url) {
      // let routeUrl = this.$router.resolve(path);
      url ? window.open(url, '_blank') : ''
    },
    // 代码格式化
    getHtml(val) {
      let a = '' + val
      let str = a
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/&quot;/g, '"')
        .replace(/&apos;/g, "'")
      return str
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 复制
    onCopy(mes) {
      this.$Clipboard({
        text: mes,
      })
        .then(() => {
          this.$message.success('复制成功')
        })
        .catch(() => {
          this.$message.error('复制失败')
        })
    },
  },
}
export default mixin
